package cn.lele.reggie.controller;

import cn.lele.reggie.common.BaseContext;
import cn.lele.reggie.common.R;
import cn.lele.reggie.dto.DishDto;
import cn.lele.reggie.entity.ShoppingCart;
import cn.lele.reggie.service.ShoppingCartService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 购物车
 */
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private HttpSession session;

    /**
     * 展示购物车
     * @return
     */
    @GetMapping("/list")
    public R<List> list(){
        Long userId = (Long)session.getAttribute("userId");
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> list = shoppingCartService.list(wrapper);
        return R.success(list);
    }

    /**
     * 添加到购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<String> insert(@RequestBody ShoppingCart shoppingCart){
        log.info("购物车dish--->");
        //添加菜品
        log.info("userId:"+BaseContext.getCurrentId());

        return shoppingCartService.addToShoppingCart(shoppingCart);
    }

    /**
     * 购物车菜品或套餐减一或删除
     * @param shoppingCart
     * @return
     */
    @PostMapping("/sub")
    public R<String> sub(@RequestBody ShoppingCart shoppingCart){
        log.info("shoppingCart---》"+shoppingCart);
        shoppingCart.setUserId(BaseContext.getCurrentId());
        Long dishId=shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(setmealId!=null,ShoppingCart::getSetmealId,setmealId);
        wrapper.eq(dishId!=null,ShoppingCart::getDishId,dishId);
        ShoppingCart one = shoppingCartService.getOne(wrapper);
        shoppingCart.setId(one.getId());
        Integer n=one.getNumber();
        if(n>1){
            shoppingCart.setNumber(one.getNumber()-1);
            shoppingCartService.updateById(shoppingCart);
        }else {
            shoppingCartService.removeById(shoppingCart);
        }

        return R.success("菜品或套餐减一");
    }
    @DeleteMapping("/clean")
    public R<String> clean(){
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        shoppingCartService.remove(wrapper);
        return R.success("清空购物车成功");
    }


}
